<script setup lang="ts">
import { computed, ref, watch, getCurrentInstance } from 'vue'
import { NScrollbar } from 'naive-ui'
import NodeService from '@/services/node.service'
import { NodeItem } from '@/types/node'

const props = defineProps<{
  position: {
    x: number,
    y: number
  },
  filter?: string
}>()
const emit = defineEmits<{
  select: [NodeItem, pos: { x: number, y: number }]
}>()

const app = getCurrentInstance()
const nodeService = new NodeService()
const nodes = ref<NodeItem[]>([])
const innerNodes = nodeService.inner_nodes as NodeItem[]
const nodeList = computed(() => [...innerNodes, ...nodes.value].filter(v => {
  if (!props.filter) {
    return true
  }
  const [io, type] = props.filter.split(':')
  if (io === 'input') {
    return v.inputs.findIndex(v1 => v1.type === 'any' || v1.type === type) > -1
  } else if (io === 'output') {
    return v.outputs.findIndex(v1 => v1.type === type || (v.type === 'const' && ['number', 'string', 'bool'].includes(type))) > -1
  }
  return false
}))
const transform = ref('translate(-1000px, 0px)')
nodeService.load().then(res => nodes.value = res)
watch(() => props.position, () => {
  const dom = app?.proxy?.$el.parentElement as HTMLDivElement
  const x = Math.min(dom.clientWidth - 103, props.position.x)
  const y = Math.min(dom.clientHeight - Math.min(nodeList.value.length, 8) * 30, props.position.y)
  transform.value = `translate(${x}px, ${y}px)`
})

function onSelect (item: NodeItem) {
  emit('select', item, props.position)
  transform.value = 'translate(-1000px, 0px)'
}
</script>
<template>
  <div class="node-context-menu" :style="{transform}" @mousedown.stop>
    <n-scrollbar style="max-height: 240px">
      <div class="node-item" v-for="item of nodeList" :key="item.id" @click.stop.prevent="onSelect(item)"> {{ item.name }}</div>
    </n-scrollbar>
  </div>
</template>
<style lang="less" scoped>
.node-context-menu {
  position: absolute;
  top: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  z-index: 10;
  min-width: 100px;
  height: fit-content;
  background-color: #3b3b3be0;
  .node-item {
    padding: 3px 12px;
    background-color: #4d4d4df4;
    cursor: pointer;
    opacity: 0.65;
    transition: opacity 0.275s;
    &:first-of-type {
      padding-top: 6px;
    }
    &:last-of-type {
      padding-bottom: 6px;
    }
    &:hover {
      opacity: 1;
    }
  }
}
</style>
